package org.brisling.mobile.service;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.util.Map;

import org.brisling.common.util.RSAUtils;
import org.brisling.mobile.config.MDomain;
import org.brisling.mobile.config.RSAConfig;
import org.springframework.security.crypto.codec.Base64;

public abstract class BaseMobileService {

	public BaseMobileService(){}
	
	protected String requestData( String keycode,String data){
			
		
		//返回临时变量定义
		String _data = null;
		
		//加密数据处理
		if( (null != keycode) && (keycode.trim().length()>1024) ){
			//根据密钥对代码获取指定密钥对
			Map<PublicKey, PrivateKey> keypaire = RSAConfig.getVerifyKeyPaire(keycode); 
			//获取密钥对私钥
			PrivateKey _prikey = RSAConfig.getPrivateKey(keypaire);
			
			
			if(_prikey instanceof RSAPrivateKey){
				try {
					_data = RSAUtils.decryptByPrivateKey(data,(RSAPrivateKey)(_prikey));
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}			
		}
		
		return _data;
	}

	/*
	 * 获取初始化密钥代码及公钥
	 */
	protected MDomain getInitKey(){
		
		MDomain obj = new MDomain();
		//获取密钥对代码
		String _code = RSAConfig.getInitKey();
		
		//获取密钥对公钥
		PublicKey pk = RSAConfig.getPublicKey(RSAConfig.getVerifyKeyPaire(_code));
		byte[] pb = pk.getEncoded();
        String pbStr =  new String(Base64.encode(pb));
		obj.setC(_code);
		
		obj.setP(pbStr);
		
		return obj;
	}
}
